<template>
  <div class="layer-filter-wrap">
    <el-input
      size="mini"
      placeholder="输入关键字进行过滤"
      v-model="filterText"
      style="margin-bottom: 8px; width: 250px"
      clearable
    />
    <el-tree
      :data="data"
      :show-checkbox="true"
      :props="defaultProps"
      :filter-node-method="filterNode"
      @check="handleCheck"
      node-key="type"
      ref="layerTreeRef"
      empty-text="暂无数据"
      highlight-current
    >
      <span class="node-item" slot-scope="{ data }">
        <el-image
          v-if="data.icon"
          fit="fill"
          :src="data.icon"
          :alt="data.label"
        >
          <i slot="error" class="el-icon-copy-document" />
        </el-image>
        <span style="margin-left: 4px">{{ data.label }}</span>
      </span>
    </el-tree>
  </div>
</template>

<script>
import layerConfig from "./layerConfig";
export default {
  props: {
    checkedKeys: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      filterText: "",
      data: layerConfig,
      defaultProps: {
        children: "children",
        label: "label",
        icon: "icon",
      },
    };
  },
  mounted() {
    if (this.checkedKeys && this.checkedKeys.length > 0) {
      this.$refs.layerTreeRef.setCheckedKeys(this.checkedKeys);
      this.handleCheck(null, {
        checkedNodes: this.$refs.layerTreeRef.getCheckedNodes(),
      });
    }
  },
  watch: {
    filterText(newValue) {
      this.$refs.layerTreeRef.filter(newValue);
    },
    data(newValue) {
      if (newValue && Array.isArray(newValue) && newValue.length > 0) {
        this.$refs.layerTreeRef.setCheckedKeys(this.checkedKeys);
        this.$nextTick(() => {
          const checkedNodes = this.$refs.layerTreeRef
            .getCheckedNodes()
            .filter(this.filterNodes);
          this.$emit("change", checkedNodes);
        });
      }
    },
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    filterNodes(node) {
      return Array.isArray(node.layers) && node.layers.length > 0;
    },
    handleCheck(_, { checkedNodes }) {
      const checkLeafNodes = checkedNodes.filter(this.filterNodes);
      this.$emit("change", checkLeafNodes);
    },
  },
};
</script>

<style>
.layer-filter-wrap {
  max-height: 300px;
  overflow: auto;
}
.node-item {
  display: flex;
  align-items: center;
}
.layer-filter-wrap /deep/ .el-image {
  display: flex !important;
  align-items: center;
}
</style>
